package com.example.network.demos.tcp.server.wuxi;

import cn.hutool.core.thread.ThreadUtil;
import com.example.network.demos.config.NetworkConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * Netty TCP服务类
 *
 * @author chenlei
 */
@Slf4j
@Component
public class NettyTcpServerWuxi implements CommandLineRunner {

    @Override
    public void run(String... args) {
        ThreadUtil.execAsync(new Runnable() {
            @Override
            public void run() {

                log.info("进行TCP服务器搭建，端口：" + NetworkConfig.getTcpServerPortWuxi());
                // 接收连接
                EventLoopGroup boss = new NioEventLoopGroup();
                // 处理信息
                EventLoopGroup worker = new NioEventLoopGroup();
                try {
                    // 定义server
                    ServerBootstrap serverBootstrap = new ServerBootstrap();
                    // 添加分组
                    serverBootstrap.group(boss, worker)
                            // 添加通道设置非阻塞
                            .channel(NioServerSocketChannel.class)
                            // 服务端可连接队列数量
                            .option(ChannelOption.SO_BACKLOG, 128)
                            // 开启长连接
                            .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                            // 流程处理
                            .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel ch) {
                                    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(8192,
                                            Unpooled.copiedBuffer("\n".getBytes())));
                                    ch.pipeline().addLast(new StringDecoder());
                                    ch.pipeline().addLast(new StringEncoder());
                                    ch.pipeline().addLast(new NettyTcpServerHandlerWuxi());
                                }
                            });
                    // 绑定端口
                    ChannelFuture cf = serverBootstrap.bind(Integer.parseInt(NetworkConfig.getTcpServerPortWuxi())).sync();
                    // 优雅关闭连接
                    cf.channel().closeFuture().sync();
                } catch (Exception e) {
                    log.error("连接错误:{}", e.getMessage());
                } finally {
                    boss.shutdownGracefully();
                    worker.shutdownGracefully();
                }
            }
        });

    }
}
